package com.yhp.web;

import com.yhp.bean.Student;
import com.yhp.dao.impl.StudentDaoImpl;
import com.yhp.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/Educational/student/getStudentList")
public class GetStudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageSize = 5;
        //1.获取参数
        //1.1模糊查询的条件
        String stuname = req.getParameter("stuname");
        String stuno = req.getParameter("stuno");
        String sex = req.getParameter("sex");
        //1.2分页数据 limit开始页 每页显示条数（固定）
        //接收页码值(当前的页码值)
        String pageIndex = req.getParameter("pageIndex");
        //如果页面没有传值，则默认查询第一页
        int Index = pageIndex==null?1:Integer.parseInt(pageIndex);
        //2.调取service方法
        StudentServiceImpl service = new StudentServiceImpl();
        List<Student> students = service.getStudents(stuname,stuno,sex==null?-1:Integer.parseInt(sex),Index,pageSize);
        //获取总页数， 总页数=总条数%每页显示条数>0?总条数/每页显示条数+1:总条数/每页显示条数
        int total = service.total(stuname, stuno, sex==null?-1:Integer.parseInt(sex));
        int totalPage = total%pageSize>0?total/pageSize+1:total/pageSize;
        //3.跳转页面
        //如果后台想给前台传数据，那么一定要在后台存值
        req.setAttribute("stulist",students);
        //所用数据只在展示页面会使用，所以存在request就可以了
        //存储模糊查询的条件
        req.setAttribute("stuname",stuname);
        req.setAttribute("stuno",stuno);
        req.setAttribute("sex",sex);
        //存储分页数据
        req.setAttribute("Index",Index);
        req.setAttribute("size",pageSize);
        req.setAttribute("total",total);
        req.setAttribute("totalPage",totalPage);
        //我们把数据存在request中,那么不能用重定向，因为重定向会使页面数据丢失，所以用转发
        req.getRequestDispatcher("list.jsp").forward(req,resp);

    }
}
